"""
项目编辑，task编辑
"""

from django.shortcuts import render, HttpResponse, redirect
from sa import models
from sa.forms.edit_project_form import Edit_ProjectModelForm
from sa.forms.task_form import TaskModelForm
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# 反向解析
from django.urls import reverse
from django.db.models import Q


@csrf_exempt
def project_view(request, p_id):
    if request.method == 'GET':
        # 编辑项目form
        project_form = Edit_ProjectModelForm(request,
                                             instance=request.project)
        # 新task的form
        task_form = TaskModelForm(request)

        context = {
            'SR_No': request.project.SR_No,
            'c_name': request.project.customer,
            'project_id': p_id,
            'owner': request.project.sa,
            'project_form': project_form,

            'task_form': task_form,
        }

        """ 访问路径如果有 ?task_id=XXX 内容，从这里增加执行 """
        # 拼接task路径 http://127.0.0.1:8001/project/22/manage/?task_id=4
        # 如果查询字符串中没有task_id参数，task_id将被设置为None。
        task_id = request.GET.get('task_id')
        # 检查task_id是否存在（即不是None或空字符串）且是否为一个有效的十进制数字字符串。
        if task_id and task_id.isdecimal():
            # .first()方法返回查询集（QuerySet）中的第一个对象，如果没有找到任何对象，则返回None。
            task_obj = models.Task.objects.filter(id=task_id, project=request.project).first()
            if task_obj:
                """ form3 task 显示和编辑使用"""
                """重点： 把拿到的 task对象: task_obj 和form3 追加到 context 字典 """
                form3 = TaskModelForm(request, instance=task_obj)
                context.update({'task_obj': task_obj, 'form3': form3})
            else:
                print(f'根据task_id: {task_id} , 没有找到对象')
        else:
            # 如果 task_id 不存在、为空或不是有效的十进制数字
            if not task_id:
                # task_id 为空或不存在
                print('未提供 task_id')
            else:
                # task_id 存在但不是有效的十进制数字
                print('task_id 必须是有效的十进制数字')

        return render(
            request, 'project_view.html', context=context)

    if request.method == 'POST':
        project_form = Edit_ProjectModelForm(
            request, instance=request.project, data=request.POST)
        if project_form.is_valid():
            instance = project_form.save(commit=False)
            instance.save()
            instance.actors.clear()
            instance.actors.add(request.sa)
            actors_to_add = project_form.cleaned_data.get('actors', [])
            for actor in actors_to_add:
                instance.actors.add(actor)
            return JsonResponse({'status': True, 'info': '项目更新成功!', 'skip': '/myproject/list/'})
        return JsonResponse({'status': False, 'error': project_form.errors})


def project_delete(request, p_id):
    """ 删除项目 """
    p_obj = models.Project.objects.filter(id=p_id, sa=request.sa).first()
    if not p_obj:
        return JsonResponse({'status': False, 'error_info': '此项目不存在或创建者不正确！'})
    p_obj.delete()
    url = reverse('my_project_list')
    return JsonResponse({'status': True, 'skip': url})


@csrf_exempt
def task_add(request, p_id):
    """ 增加task """
    if request.method == 'POST':
        task_add_form = TaskModelForm(request, data=request.POST)
        if task_add_form.is_valid():
            instance = task_add_form.save(commit=False)
            instance.project = request.project
            instance.creator = request.sa
            sub = task_add_form.cleaned_data['sub_number']
            # instance.task_type = request.project.category
            instance.software_type = request.project.software
            instance.task_number = request.project.SR_No + '.' + sub
            instance.save()
            return JsonResponse({'status': True, 'tips1': '添加Task成功~'})
        else:
            return JsonResponse({'status': False, 'error': task_add_form.errors})


def task_catalog(request, p_id):
    """ task目录 """
    # values_list: 只取需要的字段，内容是 元组 [(),(),(),]
    # values: 只取需要的字段，内容是 字典 [{},{},{},]
    data_list = models.Task.objects.filter(
        project=request.project).order_by('-id').values('id', 'task_number')
    if data_list:
        # Object of type QuerySet is not JSON serializable： QuerySet 对象不能进行 JSON 序列化
        # 需要转化为列表 list
        return JsonResponse({'status': True, 'catalog_list': list(data_list)})
    return JsonResponse({'status': False, 'error_info': 'Task暂时不存在'})


@csrf_exempt
def task_edit(request, p_id, t_id):
    """ 编辑 task """
    # task_obj = models.Task.objects.filter(id=t_id, project=p_id, creator=request.sa).first()
    # Q查询，creator 或 project__sa, 两个条件 | 或
    task_obj = models.Task.objects.filter(
        Q(id=t_id, project=p_id, creator=request.sa) |
        Q(id=t_id, project=p_id, project__sa=request.sa)
    ).first()
    if not task_obj:
        url = reverse('project_view', kwargs={'p_id': p_id})
        return redirect(url)
    form3 = TaskModelForm(request, instance=task_obj, data=request.POST)
    if form3.is_valid():
        instance = form3.save(commit=False)
        sub = request.POST.get('sub_number', '0')
        instance.task_number = request.project.SR_No + '.' + sub
        instance.save()
        url = reverse('project_view', kwargs={'p_id': p_id})
        return JsonResponse({'status': True, 'tips': '更新Task成功啦！', 'skip': url})
    else:
        return JsonResponse({'status': False, 'error': form3.errors})


def task_delete(request, p_id, t_id):
    """ 删除task """
    task_obj = models.Task.objects.filter(id=t_id, project__id=p_id).first()
    if not task_obj:
        return HttpResponse('对应task不存在', status=404)  # 建议添加状态码404
    if task_obj.creator == request.sa or task_obj.project.sa == request.sa:
        task_obj.delete()
        url = reverse('project_view', kwargs={'p_id': p_id})
        return redirect(url)
    else:
        # 若当前用户无权删除任务，则返回HTTP响应，提示无权限
        return HttpResponse('无权删除此task', status=403)  # 建议添加状态码403